const SUCCESS_CODE = 0;

/**
 * 统一相应处理，伪BFF层 很多接口返回的响应信息不统一，防止因后端规范问题导致前端工作量增加！！！！！！！故在此做统一处理
 * 目前项目后端会返回的几种响应情况,xxx代指需要的数据：[xxx]、{xxx}、{data:{xxx}}、{records:xxx}、{content:xxx}.........................沉默
 * 数据总条数涉及字段：total、totalElements
 *
 * @param response
 */
export function transferResponse(response: any) {
  // 如果后端直接返回数组，如[xxx]
  if (Array.isArray(response)) {
    return {
      code: SUCCESS_CODE,
      data: {
        list: response,
      },
      msg: 'Ok',
    };
  }

  // 如果后端直接返回数据内容对象,如{xxx}，则先进行统一响应包装
  if (response.code == undefined) {
    response = {
      code: SUCCESS_CODE,
      data: response,
      msg: 'Ok',
    };
  }

  let { code, data = {}, msg, ...rest } = response;

  if (!data) {
    data = {};
  }
  if (typeof data === 'string') {
    data = {
      value: data,
    };
  }
  // eslint-disable-next-line eqeqeq
  if (code == 'success') {
    code = 0;
  }

  if (code == 'failure' && msg && msg.includes('token无效')) {
    code = 401;
  }

  if (Array.isArray(data)) {
    data = {
      list: data,
    };
  }

  if (!data.total && data.totalElements) {
    data.total = data.totalElements;
  }

  if (data.records && Array.isArray(data.records)) {
    data.list = data.records;
    delete data.records;
  }

  if (data.content && Array.isArray(data.content)) {
    data.list = data.content;
    delete data.content;
  }

  if (data.content && Array.isArray(data.records)) {
    data.list = data.records;
    delete data.records;
  }

  if (response.code == 200 && response.flag === false) {
    code = 500;
  } else if (response.code == '200') {
    code = 0;
  }

  return {
    code,
    data: {
      ...data,
      ...rest,
    },
    msg,
  };
}
